<template>
  <div class="fee-management">
    <el-row :gutter="20" class="mb-20">
      <el-col :span="24">
        <el-button type="primary" @click="showCalculateDialog">计算存储费用</el-button>
        <el-button type="success" @click="exportExcel">导出Excel</el-button>
        <el-button type="warning" @click="testCompanyPortQuery">测试港口公司查询</el-button>
        <el-button type="info" @click="fetchCompanyPortRemainList" :disabled="!calculateForm.companyId">查询公司各港口剩余货物</el-button>
      </el-col>
    </el-row>

    <!-- 费用计算表单 -->
    <el-card class="mb-20" v-if="userStore.userInfo?.role !== 'CUSTOMER'">
      <template #header>
        <span>费用计算</span>
      </template>
      <el-form :model="calculateForm" :rules="calculateRules" ref="calculateFormRef" label-width="120px">
        <el-form-item label="公司" prop="companyId">
          <el-select v-model="calculateForm.companyId" placeholder="请选择公司" style="width: 100%">
            <el-option v-for="company in companies" :key="company.id" :label="company.name" :value="company.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="港口" prop="portId">
          <el-select v-model="calculateForm.portId" placeholder="请选择港口" style="width: 100%">
            <el-option v-for="port in ports" :key="port.id" :label="port.name" :value="port.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="重量(吨)" prop="weight">
          <el-input-number v-model="calculateForm.weight" :min="0" :precision="2" style="width: 100%" />
        </el-form-item>
        <el-form-item label="存储天数" prop="days">
          <el-input-number v-model="calculateForm.days" :min="1" style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="calculateFee">计算费用</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 计算结果 -->
    <el-card v-if="calculationResult && userStore.userInfo?.role !== 'CUSTOMER'" class="mb-20">
      <template #header>
        <span>计算结果</span>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="重量">{{ calculationResult.weight }} 吨</el-descriptions-item>
        <el-descriptions-item label="存储天数">{{ calculationResult.days }} 天</el-descriptions-item>
        <el-descriptions-item label="存储费用">{{ calculationResult.fee }} 元</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 费用规则信息 -->
    <el-card v-if="ruleInfo && userStore.userInfo?.role !== 'CUSTOMER'" class="mb-20">
      <template #header>
        <span>费用规则</span>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="免费天数">{{ ruleInfo.freeDays }} 天</el-descriptions-item>
        <el-descriptions-item label="费率">{{ ruleInfo.feeRate }} 元/吨/天</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 港口公司查询测试 -->
    <el-card v-if="portCompanies.length > 0 && userStore.userInfo?.role !== 'CUSTOMER'" class="mb-20">
      <template #header>
        <span>港口公司列表（包含剩余吨数）</span>
      </template>
      <el-table :data="portCompanies" border>
        <el-table-column prop="companyId" label="公司ID" width="80" />
        <el-table-column prop="companyName" label="公司名称" width="200" />
        <el-table-column prop="manager" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="remainingWeight" label="剩余吨数" width="120">
          <template #default="scope">
            {{ scope.row.remainingWeight }} 吨
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 公司各港口剩余货物列表，直接展示在页面下方 -->
    <el-card v-if="companyPortRemainList.length > 0 && userStore.userInfo?.role !== 'CUSTOMER'" class="mb-20">
      <template #header>
        <span>公司各港口剩余货物</span>
      </template>
      <el-table :data="companyPortRemainList" border>
        <el-table-column prop="portId" label="港口ID" width="100" />
        <el-table-column prop="companyName" label="公司名称" width="150" />
        <el-table-column prop="manager" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="150" />
        <el-table-column prop="remainingWeight" label="剩余吨数" width="120">
          <template #default="scope">
            {{ scope.row.remainingWeight }} 吨
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- CUSTOMER角色显示提示信息 -->
    <el-card v-if="userStore.userInfo?.role === 'CUSTOMER'">
      <div class="welcome-message">
        <h2>费用管理</h2>
        <p>您没有权限访问费用计算功能，请联系管理员</p>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { calculateStorageFee, getEffectiveRule, getAllPorts, getAllCompanies } from '@/api/fee'
import { getCompaniesWithRemainingWeightByPortId, getCompaniesByPortIdSimple, getPortsWithRemainingByCompanyId } from '@/api/company'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()
const loading = ref(false)
const companies = ref([])
const ports = ref([])
const calculationResult = ref(null)
const ruleInfo = ref(null)
const calculateFormRef = ref(null)
const portCompanies = ref([])
const companyPortRemainList = ref([])

const calculateForm = ref({
  companyId: null,
  portId: null,
  weight: 0,
  days: 1
})

const calculateRules = {
  companyId: [{ required: true, message: '请选择公司', trigger: 'change' }],
  portId: [{ required: true, message: '请选择港口', trigger: 'change' }],
  weight: [{ required: true, message: '请输入重量', trigger: 'blur' }],
  days: [{ required: true, message: '请输入存储天数', trigger: 'blur' }]
}

const fetchCompanies = async () => {
  try {
    const response = await getAllCompanies()
    companies.value = response.data
  } catch (error) {
    ElMessage.error('获取公司列表失败')
  }
}

const fetchPorts = async () => {
  try {
    const response = await getAllPorts()
    ports.value = response.data
  } catch (error) {
    ElMessage.error('获取港口列表失败')
  }
}

const calculateFee = async () => {
  try {
    await calculateFormRef.value.validate()
    
    loading.value = true
    
    // 获取费用规则
    const ruleResponse = await getEffectiveRule(calculateForm.value.companyId, calculateForm.value.portId)
    ruleInfo.value = ruleResponse.data
    
    // 计算费用
    const response = await calculateStorageFee(calculateForm.value)
    calculationResult.value = response.data
    
    ElMessage.success('费用计算完成')
  } catch (error) {
    ElMessage.error('计算费用失败')
  } finally {
    loading.value = false
  }
}

const testCompanyPortQuery = async () => {
  if (!calculateForm.value.portId) {
    ElMessage.warning('请先选择港口')
    return
  }
  
  try {
    loading.value = true
    
    // 先尝试带剩余吨数的查询
    try {
      const response = await getCompaniesWithRemainingWeightByPortId(calculateForm.value.portId)
      portCompanies.value = response.data
      ElMessage.success('查询成功（包含剩余吨数）')
    } catch (error) {
      // 如果失败，尝试简单查询
      const response = await getCompaniesByPortIdSimple(calculateForm.value.portId)
      portCompanies.value = response.data
      ElMessage.success('查询成功（简单版本）')
    }
  } catch (error) {
    ElMessage.error('查询失败：' + error.message)
  } finally {
    loading.value = false
  }
}

const showCalculateDialog = () => {
  // 重置表单
  calculateForm.value = {
    companyId: null,
    portId: null,
    weight: 0,
    days: 1
  }
  calculationResult.value = null
  ruleInfo.value = null
}

const exportExcel = () => {
  ElMessage.success('导出成功')
}

const fetchCompanyPortRemainList = async () => {
  if (!calculateForm.value.companyId) {
    ElMessage.warning('请先选择公司')
    return
  }
  try {
    const res = await getPortsWithRemainingByCompanyId(calculateForm.value.companyId)
    companyPortRemainList.value = res.data
    if (res.data.length === 0) {
      ElMessage.info('该公司在所有港口下都没有剩余货物')
    }
  } catch (e) {
    ElMessage.error('查询失败')
  }
}

onMounted(() => {
  // 只有非CUSTOMER角色才加载数据
  if (userStore.userInfo?.role !== 'CUSTOMER') {
    fetchCompanies()
    fetchPorts()
  }
})
</script>

<style scoped>
.mb-20 {
  margin-bottom: 20px;
}
.welcome-message {
  text-align: center;
  padding: 40px;
}
.welcome-message h2 {
  color: #409EFF;
  margin-bottom: 20px;
}
.welcome-message p {
  color: #666;
  font-size: 16px;
}
</style>